package com.privatework.common.service.classroom.impl;

import com.privatework.common.QueryConditionVo;
import com.privatework.common.constants.SystemConstant;
import com.privatework.common.converter.ClassRoomConverter;
import com.privatework.common.converter.ClassRoomUseHistoryConverter;
import com.privatework.common.converter.LeaveInfoConverter;
import com.privatework.common.entity.classroom.ClassRoom;
import com.privatework.common.entity.classroom.ClassRoomUseHistory;
import com.privatework.common.entity.classroom.QClassRoom;
import com.privatework.common.entity.classroom.QClassRoomUseHistory;
import com.privatework.common.entity.leave.LeaveInfo;
import com.privatework.common.entity.leave.QLeaveInfo;
import com.privatework.common.repository.classroom.ClassRoomRepository;
import com.privatework.common.repository.classroom.ClassRoomUseHistoryRepository;
import com.privatework.common.repository.leave.LeaveInfoRepository;
import com.privatework.common.repository.user.UserRepository;
import com.privatework.common.requestvo.classroom.ClassRoomReqVo;
import com.privatework.common.requestvo.leave.LeaveInfoReqVo;
import com.privatework.common.service.classroom.ClassRoomService;
import com.privatework.common.service.leave.LeaveService;
import com.privatework.common.utils.DateUtils;
import com.privatework.common.vo.classroom.ClassRoomHistoryResultVo;
import com.privatework.common.vo.classroom.ClassRoomResultVo;
import com.privatework.common.vo.leave.LeaveInfoResultVo;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author johnny
 * @create 2021-04-12 3:05 下午
 **/
@Service
@Slf4j
public class ClassRoomServiceImpl implements ClassRoomService {

    @Autowired
    private JPAQueryFactory queryFactory;

    @Autowired
    private LeaveInfoRepository leaveInfoRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ClassRoomUseHistoryRepository classRoomUseHistoryRepository;

    @Autowired
    private ClassRoomRepository classRoomRepository;


    @Override
    public Page<ClassRoomHistoryResultVo> listHistoryByCondition(ClassRoomReqVo classRoomReqVo,Pageable pageable) {
        List<ClassRoomHistoryResultVo> classRoomHistoryResultVos = new ArrayList<>();
        QClassRoomUseHistory qClassRoomUseHistory = QClassRoomUseHistory.classRoomUseHistory;
        JPAQuery<ClassRoomUseHistory> jpaQuery = queryFactory.selectFrom(qClassRoomUseHistory)
                .offset(pageable.getPageNumber() * pageable.getPageSize())
                .limit(pageable.getPageSize());
        jpaQuery.where(qClassRoomUseHistory.classRoomId.eq(classRoomReqVo.getId()));
        QueryResults<ClassRoomUseHistory> queryResults = jpaQuery.fetchResults();
        queryResults.getResults().forEach(classRoomUseHistory -> {
            ClassRoomHistoryResultVo classRoomHistoryResultVo = ClassRoomUseHistoryConverter.INSTANCE.domain2vo(classRoomUseHistory);
            classRoomHistoryResultVo.setCode(classRoomUseHistory.getClassRoomCode());
            classRoomHistoryResultVo.setTeacherName(classRoomUseHistory.getTeacherName());
            classRoomHistoryResultVos.add(classRoomHistoryResultVo);
        });
        return new PageImpl<>(classRoomHistoryResultVos, pageable, queryResults.getTotal());
    }

    @Override
    public Page<ClassRoomResultVo> listByCondition(ClassRoomReqVo classRoomReqVo, Pageable pageable) {

        List<ClassRoomResultVo> classRoomResultVos = new ArrayList<>();
        QClassRoom qClassRoom = QClassRoom.classRoom;
        JPAQuery<ClassRoom> jpaQuery = queryFactory.selectFrom(qClassRoom)
                .offset(pageable.getPageNumber() * pageable.getPageSize())
                .limit(pageable.getPageSize());

        fillCondition(jpaQuery, classRoomReqVo);

        QueryResults<ClassRoom> queryResults = jpaQuery.fetchResults();
        queryResults.getResults().forEach(classRoom -> {
            ClassRoomResultVo classRoomResultVo = ClassRoomConverter.INSTANCE.domain2vo(classRoom);
            List<ClassRoomUseHistory> classRoomUseHistories = classRoomUseHistoryRepository.findByClassRoomId(classRoomResultVo.getId());

            classRoomResultVo.setStatus(SystemConstant.NO_USE);
            if (CollectionUtils.isNotEmpty(classRoomUseHistories)) {
                for (ClassRoomUseHistory classRoomUseHistory : classRoomUseHistories) {
                    if (checkIsUsing(classRoomUseHistory)) {
                        classRoomResultVo.setStatus(SystemConstant.USE);
                        break;
                    }
                }
            }
            classRoomResultVos.add(classRoomResultVo);
        });
        return new PageImpl<>(classRoomResultVos, pageable, queryResults.getTotal());
    }

    @Override
    public void submitClassRoomUseInfo(ClassRoomReqVo classRoomReqVo) {

        ClassRoomUseHistory classRoomUseHistory = new ClassRoomUseHistory();
        //classRoomUseHistory.setClassInfoName(classRoomReqVo.getCode());
        classRoomUseHistory.setClassRoomCode(classRoomReqVo.getCode());
        classRoomUseHistory.setTeacherUserId(classRoomReqVo.getTeacherUserId());
        classRoomUseHistory.setUseStartTime(classRoomReqVo.getUseStartTime());
        classRoomUseHistory.setUseEndTime(classRoomReqVo.getUseEndTime());
        classRoomUseHistory.setContent(classRoomReqVo.getContent());
        classRoomUseHistory.setClassRoomId(classRoomReqVo.getId());
        classRoomUseHistory.setTeacherName(classRoomReqVo.getTeacherName());
        classRoomUseHistoryRepository.save(classRoomUseHistory);
        checkIsUsing(classRoomUseHistory);
        log.info("【submitClassRoomUseInfo ： {} }】", classRoomUseHistory);
    }



    private boolean checkIsUsing(ClassRoomUseHistory classRoomUseHistory) {
        String useStartTime = classRoomUseHistory.getUseStartTime();
        String useEndTime = classRoomUseHistory.getUseEndTime();
        Date startDate = DateUtils.formatDate(useStartTime, DateUtils.DATE_TIME_FORAT);
        Date endDate = DateUtils.formatDate(useEndTime, DateUtils.DATE_TIME_FORAT);
        Date current = new Date();
        if (startDate != null && endDate != null) {
            if (current.after(startDate) && current.before(endDate)) {
                Long classRoomId = classRoomUseHistory.getClassRoomId();
                ClassRoom classRoom = classRoomRepository.findById(classRoomId).orElse(null);
                if (classRoom != null) {
                    classRoom.setStatus(SystemConstant.USE);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void fillCondition(JPAQuery<ClassRoom> jpaQuery, QueryConditionVo queryConditionVo) {
        QClassRoom qClassRoom = QClassRoom.classRoom;
        ClassRoomReqVo classRoomReqVo = (ClassRoomReqVo) queryConditionVo;
        if (StringUtils.isNotEmpty(classRoomReqVo.getCode())) {
            jpaQuery.where(qClassRoom.code.like("%" + classRoomReqVo.getCode() + "%"));
        }
    }
}